﻿using CinemaMaestro.BusinessLayer.Contracts;
using CinemaMaestro.Common.IocContainer;
using CinemaMaestro.DataLayer.Contracts.Entities;
using CinemaMaestro.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CinemaMaestro.WebApi.Controllers
{
    public class LanguagesController : ApiController
    {
        [HttpGet]
        public IHttpActionResult GetAllLanguages()
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();

            var list = businessUoW.Languages.Read().ToList();

            List<LanguageViewModel> models = new List<LanguageViewModel>();

            foreach (var model in list)
            {
                LanguageViewModel language = model;
                models.Add(language);
            }

            return Ok(models);
        }

        [HttpGet]
        public IHttpActionResult GetLanguage(int id)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();

            var language = businessUoW.Languages.Read().FirstOrDefault(x => x.Id == id);
            if (language == null)
            {
                return NotFound();
            }
            LanguageViewModel languageVM = language;
            return Ok(languageVM);
        }

        [HttpPut]
        public IHttpActionResult UpdateLanguage(LanguageViewModel languageVM)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();
            Language language = languageVM;
            businessUoW.Languages.Update(language);
            return Ok();
        }

        [HttpDelete]
        public IHttpActionResult DeleteLanguage(int id)
        {
            var businessUow = Resolver.Get<IBusinessObjectFactory>();
            var hasDependencies = businessUow.Screenings.ScreeningHasRelationWithLanguage(id);
            if (hasDependencies)
            {
                return NotFound();
            }
            var deleted = businessUow.Languages.Delete(id);
            if (deleted)
            {
                return Ok();
            }
            return NotFound();                  
        }

        [HttpPost]
        public IHttpActionResult CreateLanguage(LanguageViewModel languageVM)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();
            Language language = languageVM;
            businessUoW.Languages.Create(language);
            return Ok();
        }

    }
}
